package org.sippr.controller;

import com.fasterxml.jackson.databind.JsonNode;
import org.sippr.pojo.Result;
import org.sippr.pojo.User;
import org.sippr.utils.EEPUtil;
import org.sippr.utils.JwtUtil;
import org.sippr.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated//字符串长度等合法性校验
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public Result<String> login(@RequestBody User user) {
        JsonNode jsonNode = EEPUtil.getUser(user.getUsername(), user.getPassword());
        if (jsonNode == null)
            return Result.error("账户或密码错误");
        else {

            String userId = null;
            String userName = null;
            try {
                userId = jsonNode.get("id").asText();
                userName = jsonNode.get("name").asText();
            } catch (Exception e) {
                return Result.error("账户或密码错误");
            }
            String token = stringRedisTemplate.opsForValue().get(userId);
            if (token != null && !token.isEmpty()) {
                return Result.success(token);
            }
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", userId);
            claims.put("username", userName);
            token = JwtUtil.gentToken(claims);
            stringRedisTemplate.opsForValue().set(userId, token, 12, TimeUnit.HOURS);
            stringRedisTemplate.opsForValue().set(token, token, 12, TimeUnit.HOURS);
            return Result.success(token);
        }


    }

//https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif

    @GetMapping("/info")
    public Result<User> info() {
        User user = new User();
        user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        user.setUsername(username);
        List<String> list = new ArrayList<>();
        list.add("admin");
        user.setRoles(list);
        user.setIntroduction("没有自我介绍！");
        return Result.success(user);
    }


    @PostMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String userId = (String) map.get("id");

        stringRedisTemplate.opsForValue().getOperations().delete(userId);
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }
}
